<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				label-width="100px"
			>
				<el-form-item :label="`${$t('common.belong_merchant')}:`">
					<el-select
						v-model="queryData.merchantId"
						size="medium"
						v-symbols
						clearable
						style="width: 180px"
						:placeholder="$t('common.select_all')"
					>
						<el-option
							v-if="isZk"
							:label="`${$t('system.all')}`"
							value="0"
						></el-option>
						<el-option
							v-for="item in merchantList"
							:key="item.id"
							:label="item.merchantName"
							:value="item.id"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="`${$t('system.name')}:`">
					<el-input
						v-model="queryData.userName"
						v-symbols
						size="medium"
						style="width: 280px"
						:placeholder="$t('common.please_enter')"
						maxlength="10"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item :label="`${$t('common.createBy')}:`">
					<el-input
						v-model="queryData.createBy"
						v-symbols
						size="medium"
						style="width: 280px"
						:placeholder="$t('common.please_enter')"
						maxlength="10"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item style="margin-left: 30px">
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="handleSearch"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="handleReset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('901021')"
						type="success"
						:disabled="loading"
						icon="el-icon-folder-add"
						size="medium"
						@click="handleEditOrCreate()"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				:data="datalist"
				style="width: 100%"
				:max-height="tableHeight"
				highlight-current-row
				:header-cell-style="getRowClass"
				border
			>
				<el-table-column
					align="center"
					type="index"
					:label="`${$t('common.serial_number')}`"
					width="70"
				>
					<template slot-scope="scope">
						<span>{{ getSerialNum(scope.$index) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="userName"
					:label="`${$t('system.name')}`"
					width="120"
				>
					<template slot-scope="scope">
						{{ scope.row.userName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="nickName"
					:label="`${$t('common.name')}`"
					width="120"
				>
					<template slot-scope="scope">
						{{ scope.row.nickName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="userType"
					align="center"
					:label="`${$t('common.number_type')}`"
				>
					<template slot-scope="scope">
						{{ typeFilter(scope.row.userType, 'userType') }}
					</template>
				</el-table-column>
				<el-table-column
					prop="merchantName"
					align="center"
					:label="`${$t('common.belong_merchant')}`"
					show-overflow-tooltip
					min-width="180"
				>
					<template slot-scope="scope">
						{{ scope.row.merchantName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="active"
					align="center"
					:label="`${$t('system.staff_manage.leave')}`"
				>
					<template slot-scope="scope">
						{{ typeFilter(scope.row.active, 'userActive') }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="createBy"
					:label="`${$t('common.createBy')}`"
					width="120"
				>
					<template slot-scope="scope">
						{{ scope.row.createBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="createAt"
					:label="`${$t('common.createAt')}`"
					width="160"
				>
					<template slot-scope="scope">
						{{ scope.row.createAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="lastLoginAt"
					:label="`${$t('system.staff_manage.login')}`"
					width="160"
				>
					<template slot-scope="scope">
						{{ scope.row.lastLoginAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					prop="googleAuthCode"
					:label="`${$t('system.staff_manage.secret')}`"
					min-width="180"
				>
					<template slot-scope="scope">
						<span>
							{{ scope.row.googleAuthCode || '-' }}
						</span>
						<el-link
							type="primary"
							@click="showGoogleAuthCode(scope.row)"
							style="padding-left: 8px;"
						>
							更换
						</el-link>
					</template>
				</el-table-column>
				<!-- <el-table-column
					align="center"
					prop="googleAuthCode"
					:label="`${$t('system.staff_manage.jellyfishSecret')}`"
					min-width="180"
				>
					<template slot-scope="scope">
						{{ scope.row.jellyfishAuthCode || '-' }}
					</template>
				</el-table-column> -->
				<!-- <el-table-column
					align="center"
					prop="googleAuthCode"
					:label="`${$t('system.staff_manage.jellyfishSecretType')}`"
					min-width="180"
				>
					<template slot-scope="scope">
						{{ scope.row.jellyfishAuthCodeType || '-' }}
					</template>
				</el-table-column> -->
				<el-table-column
					:label="`${$t('common.status')}`"
					align="center"
					width="90"
				>
					<template slot-scope="scope">
						<el-switch
							v-if="hasPermission('901022')"
							:disabled="
								scope.row.active === 0 || !scope.row.isRoleEdit
							"
							:value="
								scope.row.status === 0 ||
									scope.row.status === '1'
							"
							active-color="#13ce66"
							@change="handleStatus(scope.row)"
						></el-switch>
					</template>
				</el-table-column>
				<!-- 操作，编辑 -->
				<el-table-column
					align="center"
					fixed="right"
					:label="`${$t('common.actions')}`"
					width="330"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('901023')"
							:disabled="scope.row.active === 0"
							type="primary"
							size="medium"
							@click.native.prevent="
								openResetPwdDialog(scope.row)
							"
						>
							{{ $t('common.components.reset_password') }}
						</el-button>
						<el-button
							v-if="hasPermission('901024')"
							type="primary"
							:disabled="
								scope.row.active === 0 || !scope.row.isRoleEdit
							"
							icon="el-icon-edit"
							size="medium"
							@click.stop="handleEditOrCreate(scope.row)"
						>
							{{ $t('common.edit') }}
						</el-button>
						<el-button
							v-if="hasPermission('901025')"
							type="danger"
							icon="el-icon-delete"
							:disabled="scope.row.status === '1'"
							size="medium"
							@click="deleteUser(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
						<el-button
							v-if="hasPermission('901026')"
							type="primary"
							:disabled="
								scope.row.lockStatus === '0' ||
									scope.row.active === 0
							"
							size="medium"
							@click="UnlockStatusUser(scope.row)"
						>
							{{ $t('system.staff_manage.unlock') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				:total="total"
				:pager-count="9"
				:layout="layout"
				:page-sizes="pageSizes"
				:page-size="pageSize"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			></el-pagination>
		</template>
		<EditAccount
			v-if="editDialog.visible"
			:drawer.sync="editDialog.visible"
			:edit-data="editDialog.data"
			:is-create.sync="editDialog.IsCreate"
		/>
		<AccountUpdatePass
			:dialog.sync="resetPwdDialog.visible"
			:agentid="resetPwdDialog.agentid"
			:userName="resetPwdDialog.userName"
			:loading="updateStatusDialog.loading"
			@updatePassword="updatePassword"
		/>
		<EditGoogleAuthCode
			v-if="editGoogleAuthCode.visible"
			:drawer.sync="editGoogleAuthCode.visible"
			:googleLoading="editGoogleAuthCode.loading"
			:googleAuthCode="editGoogleAuthCode.googleAuthCode"
			@loadData="loadData"
		/>
		<GoogleKeyInput
			:isShowdialog="isShowGoogleKey"
			@getGoogleKey="submitGoogleKey($event)"
			@backPrevStep="closeGoogleKey()"
		></GoogleKeyInput>
		<el-dialog
			width="500px"
			:close-on-click-modal="false"
			center
			:visible.sync="updateStatusDialog.visible"
			:destroy-on-close="true"
			@close="closeUpdateStatusDialog"
		>
			<div slot="title" class="center">
				<span>{{ $t('system.staff_manage.confirm') }}</span>
				<span
					:class="{
						'active-color': dealerStatus.status === '1',
						'stop-color': dealerStatus.status === '0'
					}"
				>
					{{
						dealerStatus.status === '1'
							? $t('common.start_up')
							: $t('common.stop_use')
					}}
				</span>
				<span>{{ $t('system.staff_manage.this') }}?</span>
			</div>
			<el-form ref="dialogForm" :model="dialogForm">
				<el-form-item :label="$t('common.remark')" prop="remark">
					<el-input
						v-model.trim="dialogForm.remark"
						type="textarea"
						maxlength="50"
						clearable
						:placeholder="$t('system.staff_manage.less_than_50')"
						@input="handleInput"
					></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="updateStatusDialog.visible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="requestChange">
					{{ $t('common.confirm') }}
				</el-button>
			</span>
		</el-dialog>
	</main-content>
</template>

<script>
import EditAccount from './EditAccount'
import EditGoogleAuthCode from './EditGoogleAuthCode'
import AccountUpdatePass from '@/components/Dialog/UpdatePass'
import GoogleKeyInput from '@/components/GoogleKeyInput'
import list from '@/mixins/list'
import { message } from '@/utils/message'
import { getUsername, getUserInfo } from '@/utils/auth' // get token from cookie
import { NO_SPECIAL_CHAR } from '@/utils/pattern'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'

export default {
	name: routerNames.staffManage,
	components: {
		EditAccount,
		AccountUpdatePass,
		EditGoogleAuthCode,
		GoogleKeyInput,
		MainContent
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			username: getUsername(),
			loading: true,
			dealerStatus: {},
			dialogForm: {
				remark: ''
			},
			datalist: [],
			queryData: {
				userName: '',
				merchantId: '',
				createBy: ''
			},
			form: {
				originPwd: '',
				newPwd: '',
				rePwd: ''
			},
			updateStatusDialog: {
				visible: false,
				loading: false
			},
			resetPwdDialog: {
				visible: false
			},
			resetMerchantCode: '',
			editDialog: {
				visible: false,
				data: {}
			},
			editAuthCodeUserId: 0,
			editGoogleAuthCode: {
				visible: false,
				loading: false,
				googleAuthCode: ''
			},
			isShowGoogleKey: false
		}
	},
	computed: {
		isZk() {
			return this.$store.getters.isZk
		},
		merchantList() {
			return this.$store.getters.merchantList || []
		}
	},
	methods: {
		closeGoogleKey() {
			this.isShowGoogleKey = false
		},
		showGoogleAuthCode(row) {
			this.editAuthCodeUserId = row.id
			this.isShowGoogleKey = true
		},
		submitGoogleKey(googleVerifyCode) {
			const userInfo = getUserInfo()
			const params = {
				type: 1,
				merchantCode: userInfo?.merchantCode,
				userName: userInfo?.username,
				googleAuthCode: googleVerifyCode
			}
			// 第一步:检查谷歌密钥验证是否通过
			this.$api
				.checkGoogleAuthCode(params)
				.then((res) => {
					if (res?.data === true) {
						this.isShowGoogleKey = false
						// 第二步: 修改用户谷歌密钥
						this.editGoogleAuthCode = {
							visible: true,
							loading: true,
							googleAuthCode: ''
						}
						this.$api
							.updateGoogleAuthCode({
								id: this.editAuthCodeUserId
							})
							.then((res) => {
								this.editGoogleAuthCode.googleAuthCode =
									res?.data || undefined
								this.editGoogleAuthCode.loading = false
							})
							.catch(() => {
								this.editGoogleAuthCode.loading = false
							})
					} else {
						this.$message.closeAll()
						this.$message.warning('谷歌密钥验证失败')
					}
				})
				.catch(() => {})
		},
		handleInput(val) {
			this.dialogForm.remark = val.replace(NO_SPECIAL_CHAR, '')
		},
		loadData() {
			this.loading = true
			const [startTime, endTime] = this.queryData.time || []
			let params = {
				...this.queryData,
				startTime: startTime && startTime + '',
				endTime: endTime && endTime + ''
			}
			params = {
				...this.getParams(params)
			}

			this.$api
				.getUsers(params)
				.then((res) => {
					this.loading = false

					const { record, totalRecord } = res.data || {}
					this.datalist = Array.isArray(record)
						? Object.freeze(record)
						: []
					this.total = totalRecord || 0
				})
				.catch(() => (this.loading = false))
		},
		deleteUser(val) {
			const { id } = val
			this.$confirm(
				`<strong>${this.$t(
					'system.staff_manage.delete_account'
				)}?</strong><br>
				<strong style='color:red'>${this.$t(
					'system.staff_manage.delete_account_notice'
				)}</strong>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			).then(() => {
				this.$api.deleteUser({ id }).then((res) => {
					if (res?.code === 200) {
						this.$message.success(this.$t('common.delete_success'))
					} else {
						this.$message({
							type: 'error',
							message: this.$t('common.delete_fail')
						})
					}
					this.loadData()
				})
			})
		},
		closeUpdateStatusDialog() {
			this.$refs.dialogForm.resetFields()
		},
		handleStatus({ id, status, userName }) {
			this.updateStatusDialog.visible = true
			this.dealerStatus = {
				...this.dealerStatus,
				id: id,
				status: status === '1' ? '0' : '1',
				userName
			}
		},
		requestChange() {
			this.$refs.dialogForm.validate((valid) => {
				if (valid) {
					this.$api
						.updateXPSStatus({
							...this.dealerStatus,
							...this.dialogForm
						})
						.then((res) => {
							if (res?.code === 200) {
								this.$message.success(
									this.$t('common.action_success')
								)
								this.loadData()
							}
							this.updateStatusDialog.visible = false
						})
						.catch(() => {
							this.updateStatusDialog.visible = false
						})
				}
			})
		},
		handleEditOrCreate(data) {
			if (data) {
				this.editDialog.data = Object.assign({}, data)
				this.editDialog.IsCreate = false
			} else {
				this.editDialog.data = {}
				this.editDialog.IsCreate = true
			}
			this.editDialog.visible = true
		},
		openResetPwdDialog(row) {
			this.resetMerchantCode = row.agentCode
			this.resetPwdDialog.curUsername = row.userName
			this.resetPwdDialog.agentid = row.id
			this.resetPwdDialog.userName = row.userName
			this.resetPwdDialog.visible = true
		},
		updatePassword(form) {
			this.updateStatusDialog.loading = true
			return this.$api
				.modifyPassword({
					pwd: form.pwd,
					newPwd: form.newPwd,
					resPwd: form.resPwd,
					userId: form.id,
					agentCode: this.resetMerchantCode,
					userName: this.userName
				})
				.then((res) => {
					this.$message({
						message: this.$t('common.action_success'),
						type: 'success'
					})
					this.resetPwdDialog.visible = false
					if (this.resetPwdDialog.curUsername === this.username) {
						this.$store
							.dispatch('user/logout')
							.then((_) => {
								location.reload()
							})
							.catch((err) => {
								message({ message: err.msg, type: 'error' })
								this.$router.go('/')
							})
					}
				})
				.finally(() => {
					this.updateStatusDialog.loading = false
				})
		},
		handleSearch() {
			this.pageNum = 1
			this.loadData()
		},
		handleCurrentChange(val) {
			this.pageNum = val
			this.$nextTick(() => {
				this.loadData()
			})
		},
		handleReset() {
			this.queryData = {
				userName: '',
				merchantId: ''
			}
			this.pageNum = 1
			this.loadData()
		},
		UnlockStatusUser(item) {
			const { id, status } = item
			this.$confirm(
				`<strong>${this.$t(
					'system.staff_manage.unlock_account'
				)}?</strong>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.$api.unLockUser({ id, status }).then((res) => {
						if (res?.code === 200) {
							this.$message.success(
								this.$t('system.staff_manage.unlock_success')
							)
						} else {
							this.$message({
								type: 'error',
								message: this.$t(
									'system.staff_manage.unlock_fail'
								)
							})
						}
						this.loadData()
					})
				})
				.catch(() => {})
		}
	}
}
</script>
